﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using _XmlSerializer = System.Xml.Serialization.XmlSerializer;
namespace Jermaine.Serialization
{
    public class XmlSerializer : AbstractSerializer, ISerializer
    {

        public XmlSerializer() : base() { }


        public void Serialize<T>(string path, T o) where T : new() {
            base.IsNull(o);

            using (var writer = XmlWriter.Create(path)) {
                var ser = new _XmlSerializer(typeof(T));
                ser.Serialize(writer, o);
            }

        }


        public T Deserailize<T>(string path) {
            base.PathExists(path);
            var type = typeof(T);

            using (var reader = XmlReader.Create(path)) {
                var ser = new _XmlSerializer(type);
                return (T)ser.Deserialize(reader);
            }

        }


        public string Format<T>(T o) {

            using (var stream = new MemoryStream()) {
                var ser = new _XmlSerializer(typeof(T));
                ser.Serialize(stream, o);
                return Encoding.Default.GetString(stream.ToArray());
            }


        }

        public T Parse<T>(string stringObject) {
            var bytes = Encoding.Default.GetBytes(stringObject);
            using (var stream = new MemoryStream(bytes)) {
                var ser = new _XmlSerializer(typeof(T));
                return (T)ser.Deserialize(stream);
            }
        }
    }
}
